package cn.yhjz.platform.system.config.security;

import cn.yhjz.common.AjaxResponse;
import cn.yhjz.platform.system.entity.SysUser;
import cn.yhjz.platform.system.repository.UserPrincipalRepository;
import cn.yhjz.platform.system.util.LoginUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class LogoutHandler implements LogoutSuccessHandler {
    @Autowired
    private UserPrincipalRepository userPrincipalRepository;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        AjaxResponse res = AjaxResponse.success("登出成功");
        response.setContentType("application/json;charset=utf-8");
        //清空redis中的token信息
        SysUser sysUser = LoginUtil.getCurrentUser();
        log.info("登出：{}", sysUser);
        if (null != sysUser) {
            userPrincipalRepository.remove(sysUser.getUserCode());
        }
        response.getWriter().write(JSONUtil.toJsonStr(res));
    }
}
